import Cookies from 'js-cookie'
import ApiAuth from '../api/ApiAuth';
import StrUtil from './StrUtil';
import System from './System';

export default class CookieUtil {

    /**
     * 设置
     */
    static set(key:string,value:string){
        Cookies.set(key, value)
    }

    /**
     * 获取指定值
     */
    static get(key:string) : string{
        return Cookies.get(key) || null
    }

    /**
     *  获取token
     * @return 字符串
     */
    static async getToken() : Promise<string>{
        const tokenT = Cookies.get("token") || null
        let tokenTimeT = Cookies.get("tokenTime") || null
        if(StrUtil.isNull(tokenT))
            return ""
        System.$store.system.token = tokenT
        tokenTimeT = parseInt(tokenTimeT)
        let thisTime = new Date().getTime()
        let thisTimeSub = thisTime - tokenTimeT
        // console.log(tokenTimeT,thisTime,thisTimeSub);
        if(thisTimeSub>0){
            System.$store.system.tokenRefresh = true
            // console.log("验证码超时");
            await this.refrenshToken()
        }
    
        return System.$store.system.token
    }

    static refreshNum:number = 0

    static async refrenshToken(){
        return await new Promise( (resolve) =>{ApiAuth.loginRefreshToken().then((data:any)=>{
            // console.log("刷新认证获取",data);
            data = data.data
            System.$store.system.token = data.access
            this.setToken(data.access,data.expire)
            this.refreshNum = 0
            System.$store.system.tokenRefresh = false
            resolve(true)
        }).catch((e:any)=>{
            this.refreshNum++
            // console.log("刷新认证出现问题",e);
            if(this.refreshNum > 5){
                System.$store.system.tokenRefresh = false
                this.refreshNum = 0
            }else{
                setTimeout(()=>{
                    return this.refrenshToken()
                },500)
            }
        })})
    }

    static setToken(token:string,tokenTime:string){
        this.set("token",token)
        this.set("tokenTime",tokenTime)
        System.$store.system.token = token
    }

}